<template>
  <a-space direction="vertical" style="width: 100%">
    <a-card :title="pageTitle">
      <template #extra>最新數據:{{ overviewData.latestDate }}</template>
      <div class="statistics">
        <a-row>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="當月銷售額"
                :value="overviewData.currentMonth"
                :precision="2"
                prefix="$"
                suffix="w"
              >
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="比上月新增"
                :value="overviewData.currentMonthRate"
                :precision="2"
                suffix="%"
                :value-style="{ color: '#cf1322' }"
              >
                <template #prefix>
                  <arrow-up-outlined v-if="overviewData.currentMonthRate > 0" />
                  <arrow-down-outlined
                    v-else-if="overviewData.currentMonthRate < 0"
                  />
                </template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="當月診症數"
                :value="overviewData.currentMonthConsultCount"
                suffix="個"
              >
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="當日銷售額"
                :value="overviewData.currentDay"
                :precision="2"
                prefix="$"
                suffix="w"
              >
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="比昨日新增"
                :value="overviewData.currentDayRate"
                :precision="2"
                suffix="%"
                :value-style="{ color: '#cf1322' }"
              >
                <template #prefix>
                  <arrow-up-outlined v-if="overviewData.currentDayRate > 0" />
                  <arrow-down-outlined
                    v-else-if="overviewData.currentDayRate < 0"
                  />
                </template>
              </a-statistic>
            </a-card>
          </a-col>

          <a-col :span="6">
            <a-card>
              <a-statistic
                title="當日診症數"
                :value="overviewData.currentDayConsultCount"
                suffix="個"
              >
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <p>銷售數據</p>
      <a-radio-group
        v-model:value="timeRange"
        @change="handleTimeRangeChange"
        style="margin-bottom: 16px"
      >
        <a-radio-button value="7d">近7天</a-radio-button>
        <a-radio-button value="1m">近一月</a-radio-button>
        <a-radio-button value="3m">近三月</a-radio-button>
        <a-radio-button value="6m">近六月</a-radio-button>
        <a-radio-button value="1y">近一年</a-radio-button>
      </a-radio-group>
      <a-spin :spinning="loading1">
        <div ref="chartContainer" class="chart"></div>
      </a-spin>
    </a-card>
    <a-row :gutter="16">
      <a-col :span="12">
        <a-card title="當月銷售排名">
          <a-table
            :columns="doctorRankingColumns"
            :data-source="doctorRankingData"
            :pagination="false"
            :loading="loading2"
          >
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.key === 'rank'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'sales'">
                $ {{ record.sales }} w
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <a-col :span="12">
        <a-card title="系統消息" v-if="router.hasRoute('SystemMessage')">
          <template #extra>
            <RouterLink :to="{ name: 'SystemMessage' }"> 更多</RouterLink>
          </template>
          <a-list
            item-layout="horizontal"
            size="large"
            :data-source="messageData"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a-button
                    type="link"
                    block
                    size="small"
                    @click="handleView(item.id)"
                    >查看</a-button
                  >
                </template>

                <a-list-item-meta :title="item.title">
                  <template #description>
                    {{
                      item.content.length < 50
                        ? item.content
                        : item.content.slice(0, 50).concat("...")
                    }}
                  </template>
                </a-list-item-meta>
                {{ $formatDate(item.cratedAt) }}
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </a-space>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, reactive } from "vue";
import { ArrowUpOutlined, ArrowDownOutlined } from "@ant-design/icons-vue";
import { Line } from "@antv/g2plot";
import { useAuthUserStore } from "@/store/authUserStore";
import { salesApi, systemMessageApi } from "@/api";
import { useRouter } from "vue-router"; // 新增路由導入

const authUserStore = useAuthUserStore();
const user = authUserStore.userInfo;

const pageTitle = ref("Hi , " + user.username); // 簡體→繁體

const overviewData = reactive({
  latestDate: "未獲取",
  currentMonth: 0,
  currentDay: 0,
  currentMonthRate: 0,
  currentDayRate: 0,
  currentDayConsultCount: 0,
  currentMonthConsultCount: 0,
});

// 獲取overview數據
const fetchOverviewData = async () => {
  try {
    const { data } = await salesApi.getOverviewData();
    overviewData.latestDate = data.latestDate || "未獲取";
    overviewData.currentMonth = data.currentMonth || 0;
    overviewData.currentDay = data.currentDay || 0;
    overviewData.currentMonthRate = data.currentMonthRate || 0;
    overviewData.currentDayRate = data.currentDayRate || 0;
    overviewData.currentDayConsultCount = data.currentDayConsultCount || 0;
    overviewData.currentMonthConsultCount = data.currentMonthConsultCount || 0;
  } catch (error) {
    console.error("獲取概覽數據失敗", error);
  }
};
const timeRange = ref("7d");
// 自定義測試數據（7天）
const saleData = ref<Array<{ date: string; sales: number }>>([]);
watch(
  () => [...saleData.value], // 更精確的監聽方式
  (newData) => {
    if (chart.value) {
      chart.value.changeData(newData);
    }
  }
);

const doctorRankingColumns = [
  {
    title: "排名",
    key: "rank",
  },
  {
    title: "醫師姓名",
    dataIndex: "doctorName",
    key: "doctorName",
  },
  {
    title: "當月銷售額",
    dataIndex: "sales",
  },
];

const doctorRankingData = ref([]);

const loading2 = ref(false);
const fetchDoctorRankingData = async (params?: any) => {
  loading2.value = true;
  try {
    const { data } = await salesApi.getDoctorRanking(params);
    doctorRankingData.value = data || [];
  } catch (error) {
    console.error("獲取醫師排名數據失敗", error);
  } finally {
    loading2.value = false;
  }
};

const messageData = ref([]);
systemMessageApi.getSystemMessageList({ pageSize: 10 }).then((res) => {
  messageData.value = res.data.list.slice(0, 3);
});

//獲取最近的銷售數據
const loading1 = ref(false);
const fetchRecentSalesData = async (range: string = "7d") => {
  loading1.value = true;
  try {
    const { data } = await salesApi.getRecentSalesData({ timeRange: range });
    saleData.value = data || [];
  } catch (error) {
    console.error("獲取最近銷售數據", error);
  } finally {
    loading1.value = false;
  }
};

const handleTimeRangeChange = (e: any) => {
  fetchRecentSalesData(e.target.value);
};

const chart = ref<Line | null>(null);
const chartContainer = ref<HTMLDivElement>();

onMounted(async () => {
  if (!chartContainer.value) return;

  chart.value = new Line(chartContainer.value, {
    data: saleData.value,
    xField: "date",
    yField: "sales",
    color: "#1890ff",
    smooth: true, // 添加平滑效果
    lineStyle: {
      lineWidth: 3,
      opacity: 0.8,
    },
    point: {
      size: 3,
      shape: "circle", // 自定義點的形狀, 支持 'circle' | 'rect' | 'diamond' | 'square' | 'triangle' | 'hexagon' | 'star' | 'wye' | 'polygon'
      style: {
        fill: "#fff", //transparent透明
        stroke: "#1890ff",
        lineWidth: 2,
      },
    },
    // label: {
    //   style: {
    //     fill: '#666',
    //     fontSize: 12,
    //   },
    //   formatter: (item) => `${item.sales}萬`,
    // },
    xAxis: {
      label: {
        style: {
          fill: "#666",
          fontSize: 12,
        },
      },
      tickCount: 7, // 控制x軸刻度數量
    },
    yAxis: {
      label: {
        formatter: (v) => `$${v} w`,
      },
    },
    tooltip: {
      showMarkers: false,
      formatter: (datum) => ({
        name: "銷售額",
        value: `$ ${datum.sales} w`,
      }),
    },
    interactions: [{ type: "element-active" }],
  });

  chart.value.render();
  try {
    fetchRecentSalesData(timeRange.value);
    fetchOverviewData();
    fetchDoctorRankingData();
  } catch (error) {
    console.error("數據獲取過程中出錯:", error);
  }
});

onBeforeUnmount(() => {
  chart.value?.destroy();
});

const router = useRouter(); // 初始化路由實例

// 新增：查看消息詳情跳轉函數
const handleView = (messageId: number) => {
  router.push({ path: `/system-message/${messageId}` }); // 根據實際路由配置調整路徑
};
</script>

<style scoped>
.statistics {
  margin-bottom: 20px;
}
</style>
